package com.hh.recommend;

import cn.hutool.core.collection.CollectionUtil;
import com.hh.entity.domain.ItemMetadata;
import com.hh.mapper.ItemMetadataMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * com.hh.recommend
 *
 * @author
 * @version 0.0.1
 * @date 2025/7/25
 **/
@Service
public class ColdStartHandler {

    @Autowired
    private ItemMetadataMapper itemMetadataMapper;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    // 基于内容相似度计算
    public List<Long> contentBasedRecommend(ItemMetadata item, int topN) {
        List<ItemMetadata> allItems = itemMetadataMapper.selectList(null);

        Map<Long, Float> similarityScores = new HashMap<>();
        allItems.forEach(candidate -> {
            if (!candidate.getItemId().equals(item.getItemId())) {
                float sim = calculateContentSimilarity(item, candidate);
                similarityScores.put(candidate.getItemId(), sim);
            }
        });

        return similarityScores.entrySet().stream()
                .sorted(Map.Entry.comparingByValue(Comparator.reverseOrder()))
                .limit(topN)
                .map(Map.Entry::getKey)
                .collect(Collectors.toList());
    }

    private float calculateContentSimilarity(ItemMetadata item1, ItemMetadata item2) {
        // Jaccard相似度计算
        Set<String> tags1 = new HashSet<>(Integer.parseInt(item1.getTags()));
        Set<String> tags2 = new HashSet<>(Integer.parseInt(item2.getTags()));

        int intersection = CollectionUtil.intersection(tags1, tags2).size();
        int union = tags1.size() + tags2.size() - intersection;

        return union == 0 ? 0 : (float) intersection / union;
    }
}
